<?php
/**
 * @author ANHTAM
 */
// Require module for controller
require_once(LIB_DAO_DIR . "/MUser.class.php");

class User_Controller extends ControllerAdmin {
	/**
     * - Constructor
     */
    public function __construct() {
    	parent::__construct();
        $this->errorArr = array();
    }
    
    /**
     * actionIndex
     * - page index of controller
     */
	public function actionIndex() {
    	
    	// Process init
        $objView = new ViewAdmin();
        $this->tpl_title = 'List all user';
        $this->cQL = true;
        $this->flagMUser = true;
        
		if (!$this->loginFlag || $this->dataUser['quyen'] > '1') {
        	FunctionCommon::sendRedirect();
        }
        
        $this->getGet = FunctionCommon::getGet(array('type', 'sort', 'value'));
        $this->getPost = array('hoten'=>'', 'email'=>'', 'nickname'=>'', 'phone'=>'');
		
        $this->sort = ($this->getGet['sort'] != '') ? $this->getGet['sort'] : 'insert_at';
        $this->valueSort = ($this->getGet['value'] != '') ? $this->getGet['value'] : 'DESC';
        $this->strSort = '&sort='.$this->sort.'&value='.$this->valueSort;
        
		// List all
        if ($this->getGet['type'] == 's') {
    		$this->getPost = Session::Get("GETPOST");
    		$data = Session::Get("RESULTDONHANG");
    	} else {
    		$ojbMUser = new MUser();
    		$arrParam = array('m' => 'user', 'sort' => $this->sort, 'value' => $this->valueSort);
    		$arrField = array('id', 'nickname', 'hoten', 'email', 'phone', 'insert_at');
        	$data = FunctionCommon::paging($ojbMUser, $arrParam, $arrField, array(), array($this->sort=>$this->valueSort));
    	}
        $arrContent = $data["data"];
		$this->arrContent = array();
		$this->currPage = '';
		$this->numberPage = '';
		$this->strPaging = '';
		if (count ($arrContent) > 0) {
			foreach ($arrContent as $content) {
				$this->arrContent[] = $content;
			}
			$this->currPage = $data["currPage"];
			$this->numberPage = $data["numberPage"];
			$this->strPaging = $data["strPaging"];
		}
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
    /**
     * actionLogin
     * - page login of controller
     */
    public function actionLogin() {
    	
    	// Process init
        $objView = new ViewAdmin();
        $this->tpl_title = 'Access Admin';
        $this->countLogin = (Session::Get("TOTALLOGIN") > 0) ? Session::Get("TOTALLOGIN") : 0;
        $this->activeLogin = false;

        $mUser = new MUser();
        $getPost = FunctionCommon::getPost(array('nickname', 'password'));
        if (isset($_POST['Sub'])) {
	        if ($getPost['nickname'] != null && $getPost['password'] != null) {
	        	if (isset($_POST['captcha'])) {
	        		$captcha = $_POST['captcha'];
	        		if ($captcha == '') {
	        			$this->errorArr['captcha'] = "Bạn chưa nhập mã ở hình bên";
	        		} else {
	        			if ($captcha != $_SESSION['CAPTCHA']) {
	        				$this->errorArr['captcha'] = "Bạn nhập chưa đúng mã";
	        			}
	        		}
	        	}
	        	$checkUser = $mUser->checkLogin($getPost['nickname'], md5($getPost['password']));
	        	if (is_array($checkUser) && !empty($checkUser) && $checkUser['quyen'] <= '2' && count ($this->errorArr) == 0) {
	        		Session::Set("MUSER", $checkUser);
	        		Session::Remove("TOTALLOGIN");
	        		$this->activeLogin = true;
	        		//FunctionCommon::sendRedirect('index.php?m=home&a=index'.constants::$pathUrl);
	        	}
	        	$this->errorArr['nickname'] = "Bạn nhập chưa đúng nickname, password";
	        } else {
	        	$this->errorArr['nickname'] = "Bạn chưa nhập nickname hoặc password";
	        }
	        Session::Set("TOTALLOGIN", ($this->countLogin + 1));
        }
        
        $dataGet = FunctionCommon::getGet(array('type'));
        if ($dataGet['type'] != null) {
        	Session::Remove("MUSER");
        }
        
        $this->dataUser = Session::Get("MUSER");
        if (is_array($this->dataUser) && !empty($this->dataUser)) {
        	$this->loginFlag = true;
        }
        
        $this->countLogin = (Session::Get("TOTALLOGIN") > 0) ? Session::Get("TOTALLOGIN") : $this->countLogin;

        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionEdit
     * - page edit of controller
     */
    public function actionEdit() {
    	
    	// Process init
        $objView = new ViewAdmin();
        $this->tpl_title = '';
   		$this->infoUser = array('gioitinh'=>'', 'hoten'=>'', 'ngaysinh'=>'', 'congty'=>'', 'tinh'=>'', 'diachi'=>'', 'phone'=>'', 'phone2'=>'', 'email'=>'', 'fax'=>'', 'web'=>'', 'nickname'=>'', 'quyen'=>'');
   		$this->buttonIn = false;
    	if (!$this->loginFlag || $this->dataUser['quyen'] > '1') {
        	FunctionCommon::sendRedirect();
        }
        
        $getPost = FunctionCommon::getPost(array('quyen', 'mode', 'itemID', 'type'));
        $this->id = $getPost['itemID'];
        //echo "<pre>";print_r($getPost);exit;
        $ojbMUser = new MUser();
        if ($getPost['mode'] != '' && $getPost['mode'] == 'edit') {
        	$this->buttonIn = true;
        	$ojbMUser->setAttribute("quyen", $getPost['quyen']);
        	$ojbMUser->update(array('id'=>$this->id));
        } else {
        	$this->infoUser = $ojbMUser->getByPrimaryKey($this->id);
        }

        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionSendMail
     */
    public function actionSendmail() {
    	
    	// Process init
        $objView = new ViewAdmin ();
        $this->tpl_title = 'Send mail cho khách hàng';
        $this->arrMail = array();
        $this->buttonCot= false;
        
    	if (!$this->loginFlag || $this->dataUser['quyen'] > '1') {
        	FunctionCommon::sendRedirect();
        }
        
        $getGet = FunctionCommon::getGet(array('mail'));
        $this->getPost = array('tieude'=>'', 'noidung'=>'', 'captcha'=>'', 'emailA'=>'');
        if ($getGet['mail'] != '') {
        	$this->arrMail[] = $getGet['mail'];
        }
        
        if (isset($_POST['mode']) && $_POST['mode'] == 'sendmail') {
        	$mailArr = FunctionCommon::getPost(array('emailA'));
        	if (count ($mailArr['emailA']) > 0) {
        		foreach ($mailArr['emailA'] as $mail) {
        			$this->arrMail[] = $mail;
        		}
        	} else {
        		$this->errorArr[] = 'Chưa có mail nào dc chọn';
        	}
        }
        
        if (isset($_POST['butSub'])) {
        	$this->getPost = FunctionCommon::getPost(array_keys($this->getPost));
        	if ($this->getPost['captcha'] != $_SESSION['CAPTCHA']) {
        		$this->errorArr['captcha'] = 'Bạn nhập mã chưa đúng';
        	}
        	if (count ($this->getPost['emailA']) > 0) {
        		foreach ($this->getPost['emailA'] as $mail) {
        			$this->arrMail[] = $mail;
        		}
        	} else {
        		$this->errorArr[] = 'Chưa có mail nào dc chọn';
        	}
        	
        	if (count ($this->errorArr) == 0 && count ($this->arrMail) > 0) {
        		$sendMai = array();
        		foreach ($this->arrMail as $mal) {
        			$sendMai[] = array('name'=>'MUA THE NHANH', 'mail'=>$mal);
        		}
        		$subJ = $this->getPost['tieude'];
        		$body = $this->getPost['noidung'];
        		$checkSend = FunctionCommon::sendMail($sendMai, $subJ, $body, 'bcc');
        		if ($checkSend) {
        			$this->buttonCot = true;
        		} else {
        			$this->errorArr = array($checkSend);
        		}
        	}
        }
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionEcode
     * - page edit of controller
     */
    public function actionEcode() {
    	
    	// Process init
        $objView = new ViewAdmin();
        $this->tpl_title = '';
        $this->cQLe = true;
        $this->buttonEc = false;
        $this->flagMUser = true;
        
    	if (!$this->loginFlag || $this->dataUser['quyen'] > '1') {
        	FunctionCommon::sendRedirect();
        }
        
    	$mUser = new MUser();
        $this->getPost = FunctionCommon::getPost(array('passOld', 'passNew', 'passNew2'));
        if (isset($_POST['butSub'])) {
        	if ($this->getPost['passNew'] != $this->getPost['passNew2']) {
        		$this->errorArr['passOld'] = 'Bạn nhập 2 mật mã không trùng nhau';
        	} 
        	if(md5($this->getPost['passOld']) != $this->dataUser['pass']) {
        		$this->errorArr['passOld2'] = 'Bạn nhập pass ko đúng';
        	} 
        	if (count($this->errorArr) == 0) {
        		$mUser->setAttribute('pass', md5($this->getPost['passNew']));
        		$mUser->update(array('id' => $this->dataUser['id']));
        		$this->buttonEc = true;
        	}
        }

        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
    /**
     * actionResetPass
     * - Using ajax
     */
    public function actionResetPass() { 
    	$result = false;
		$mUser = new MUser();
        $getPost = FunctionCommon::getPost(array('id'));
        if ($getPost['id'] != '') {
	        // Lay thong tin user
	        $getOneName = $mUser->getByPrimaryKey($getPost['id']);
	        if (count ($getOneName) > 0) {
	        	// Set pass new
	        	$passNew = substr(md5(microtime()), 0, 6);

	        	// Send mail
	        	$sendMai = array(array('name'=>'MuaTheNhanh', 'mail'=>$getOneName['email']));
        		$subJ = "Cấp lại mật khẩu tại MuaTheNhanh";
        		$body = " + NickName : " . $getOneName['nickname'] . "\n ".
        				"+ Password new : " . $passNew . "\n\n ".
        				"+ Ngày đăng ký : " . FunctionCommon::convertDate($getOneName['insert_at']) . "\n ".
        				"+ Ngày cấp lại : " . FunctionCommon::convertDate(date('Y-m-d H:i:s')) . "\n ".
        				"+ Được cấp bởi : Admin \n ";
        		$checkSend = FunctionCommon::sendMail($sendMai, $subJ, $body);
        		if ($checkSend) {
        			$mUser->setAttribute('pass', md5($passNew));
        			$mUser->update(array('id' => $getOneName['id']));
        			$result = true;
        		}
	        }
        }
        if ($result) {
        	echo "1";
        } else {
        	echo "0";
        }
    }

	/**
    * actionSearch
    */
	public function actionSearch() {
		require_once(LIB_CORE_DIR . "/Paging.class.php");
		$objPaging = new Paging();
		$ojbMUser = new MUser();
		
		$getGet = FunctionCommon::getGet(array('sort', 'value'));
		$sort = ($getGet['sort'] != '') ? $getGet['sort'] : 'insert_at';
        $valueSort = ($getGet['value'] != '') ? $getGet['value'] : 'DESC';
        
		$arrParam = array('m'=>'user', 'a'=>'search', 'sort' => $sort, 'value' => $valueSort);
		
		$getPost = FunctionCommon::getPost(array('hoten', 'email', 'nickname', 'phone'));
		$sqlKD = "";
		if (isset($_POST['SubSearch'])) {
			if ($getPost['hoten'] != '') {
				$sqlKD .= " AND hoten like '%".$getPost['hoten']."%'";
			}
			if ($getPost['email'] != '') {
				$sqlKD .= " AND email like '%".$getPost['email']."%'";
			}
			if ($getPost['nickname'] != '') {
				$sqlKD .= " AND nickname like '%".$getPost['nickname']."%'";
			}
			if ($getPost['phone'] != '') {
				$sqlKD .= " AND phone like '%".$getPost['phone']."%'";
			}

			Session::Set("sqlKD", $sqlKD);
			Session::Set("GETPOST", $getPost);
		} else {
			$sqlKD = Session::Get("sqlKD");
		}
		
		$sql1 = "SELECT COUNT(id) as count_data FROM m_user WHERE 1=1" . $sqlKD;
	    // Get total record of content menu
	    $rsField = $ojbMUser->execute($sql1, ADODB_FETCH_ASSOC);
		$totalRecord = $rsField->fields['count_data'];
		 // Get page current
        if (isset($_REQUEST["pageNo"])) {
        	$currentPage = $_REQUEST["pageNo"];
        }
        else {
            $currentPage = 1;
        }
		$numberRecord = 10;
        // get page number
		if (!is_null($numberRecord) && $numberRecord != 0) {
			$numberPage = ceil($totalRecord / $numberRecord);
		} else {
			$numberPage = 0;
		}
		// get start record
		$startRecord = ($currentPage - 1) * $numberRecord;

        // get array paging
		$arrPage = $objPaging->getArrPaging($currentPage, $numberPage);
		// get string page
		$strPaging = $objPaging->getStrPaging($arrPage, $currentPage, $numberPage, $arrParam);

        // Get all content menu
        $rsField = false;
        $sql2 = "SELECT id, nickname, hoten, email, phone, insert_at FROM m_user WHERE 1=1" . $sqlKD . " ORDER BY " . $sort . " " . $valueSort . " LIMIT " . $startRecord . ", " . $numberRecord;
        //echo $sql2;
        $rsField = $ojbMUser->execute($sql2, ADODB_FETCH_ASSOC);
		$content = array();
		if($rsField) {
            while (! $rsField->EOF && $item = $rsField->FetchRow()) { 
                $content[] = $item;
            }
        }

        $no = $startRecord + 1;
		$result = array("total"=>$totalRecord,
						"data"=>$content,
						"currPage"=>$currentPage,
						"numberPage"=>$numberPage,
						"strPaging"=>$strPaging,
						"no"=>$no);
		Session::Set("RESULTDONHANG", $result);
		//echo "<pre>";print_r($result);exit;
		FunctionCommon::sendRedirect("index.php?m=user&a=index&type=s&sort=" . $sort . "&value=" . $valueSort . constants::$pathUrl . "#content");
	}
}
?>

